#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试对话持久化功能
"""

import requests
import json
import time

def test_chat_persistence():
    """测试对话持久化功能"""
    base_url = "http://localhost:8080"
    
    print("🧪 测试对话持久化功能")
    print("=" * 50)
    
    # 1. 创建工作区
    print("1. 创建工作区...")
    workspace_data = {
        "name": "测试工作区",
        "description": "用于测试对话持久化"
    }
    
    try:
        response = requests.post(f"{base_url}/api/workspaces", json=workspace_data)
        if response.status_code == 201:
            workspace = response.json()
            workspace_id = workspace['id']
            print(f"✅ 工作区创建成功: {workspace['name']} (ID: {workspace_id[:8]}...)")
        else:
            print(f"❌ 工作区创建失败: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ 工作区创建异常: {e}")
        return False
    
    # 2. 创建分析会话
    print("\n2. 创建分析会话...")
    session_data = {
        "workspace_id": workspace_id,
        "name": "测试会话",
        "description": "用于测试对话持久化"
    }
    
    try:
        response = requests.post(f"{base_url}/api/sessions", json=session_data)
        if response.status_code == 201:
            session = response.json()
            session_id = session['id']
            print(f"✅ 会话创建成功: {session['name']} (ID: {session_id[:8]}...)")
        else:
            print(f"❌ 会话创建失败: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ 会话创建异常: {e}")
        return False
    
    # 3. 发送AI问题（模拟前端调用）
    print("\n3. 发送AI问题...")
    question_data = {
        "question": "你好，这是一个测试问题",
        "conversation_id": session_id,
        "include_logs": False
    }
    
    try:
        response = requests.post(f"{base_url}/ai/ask", json=question_data)
        if response.status_code == 200:
            answer = response.json()
            print(f"✅ AI回答成功，回答长度: {len(answer.get('answer', ''))}")
        else:
            print(f"❌ AI回答失败: {response.status_code}")
            print(f"错误信息: {response.text}")
            return False
    except Exception as e:
        print(f"❌ AI回答异常: {e}")
        return False
    
    # 4. 检查对话历史是否保存
    print("\n4. 检查对话历史...")
    try:
        response = requests.get(f"{base_url}/api/sessions/{session_id}/conversations")
        if response.status_code == 200:
            conversations = response.json()
            print(f"✅ 对话历史获取成功，共 {len(conversations)} 条记录")
            
            for i, conv in enumerate(conversations):
                print(f"   记录 {i+1}: {conv['message_type']} - {conv['content'][:50]}...")
        else:
            print(f"❌ 对话历史获取失败: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ 对话历史获取异常: {e}")
        return False
    
    # 5. 再次发送问题
    print("\n5. 发送第二个问题...")
    question_data2 = {
        "question": "这是第二个测试问题",
        "conversation_id": session_id,
        "include_logs": False
    }
    
    try:
        response = requests.post(f"{base_url}/ai/ask", json=question_data2)
        if response.status_code == 200:
            answer = response.json()
            print(f"✅ 第二个AI回答成功，回答长度: {len(answer.get('answer', ''))}")
        else:
            print(f"❌ 第二个AI回答失败: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ 第二个AI回答异常: {e}")
        return False
    
    # 6. 再次检查对话历史
    print("\n6. 再次检查对话历史...")
    try:
        response = requests.get(f"{base_url}/api/sessions/{session_id}/conversations")
        if response.status_code == 200:
            conversations = response.json()
            print(f"✅ 对话历史更新成功，共 {len(conversations)} 条记录")
            
            for i, conv in enumerate(conversations):
                print(f"   记录 {i+1}: {conv['message_type']} - {conv['content'][:50]}...")
        else:
            print(f"❌ 对话历史更新失败: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ 对话历史更新异常: {e}")
        return False
    
    print("\n" + "=" * 50)
    print("🎉 对话持久化测试完成！")
    return True

if __name__ == "__main__":
    success = test_chat_persistence()
    if success:
        print("✅ 所有测试通过，对话持久化功能正常工作")
    else:
        print("❌ 测试失败，请检查错误信息")
